<?php
/**
 * Create By: PhpStorm
 * User: niechenguang
 * File: Circle.php
 * Date: 2017/1/2
 * Time: 23:13
 */
namespace app\api\model\dao;

use app\library\Flag;
use think\Model;
use think\Db;

class CircleCategory extends Model
{
    protected $table = 'circle_category';

    protected $pk = 'id';

    protected $autoWriteTimestamp = true;

    /**
     * 创建圈子分类
     *
     */
    public function addCircleCategory($arrInput)
    {
        if (!empty($arrInput['extend_info'])) {
            if (is_array($arrInput['extend_info'])) {
                $arrInput['extend_info'] = json_encode($arrInput['extend_info']);
            }
        } else {
            $arrInput['extend_info'] = '[]';
        }

        unset($arrInput[$this->pk]);

        $this->data($arrInput);
        $this->save();
        return $this->data[$this->pk];
    }

    /**
     * 删除圈子分类
     *
     */
    public function delCircleCategory($arrInput)
    {

        $this->allowField(true);

        $conds = [];

        foreach ($arrInput as $key => $val) {
            if (in_array($key, $this->field)) {
                $conds[$key] = $val;
            }
        }

        if (empty($conds)) {
            return true;
        }

        $data = [
            'is_delete' => Flag::CONST_CIRCLECATEGORY_DELETED,
            'update_time' => time(),
        ];

        return Db::table($this->table)->where($conds)->update($data);
    }

    /**
     * 获取圈子分类列表
     *
     */
    public function getCircleCategory($conds = [], $fields = [], $offset = 0, $limit = 10000, $orderby = '')
    {
        $this->allowField(true);

        $arrCond = [];
        foreach ($conds as $key => $val) {
            if (in_array($key, $this->field)) {
                $arrCond[$key] = $val;
            }
        }
        empty($arrCond) && $arrCond = '1=1';

        $arrField = [];
        foreach ($fields as $val) {
            if (in_array($val, $this->field)) {
                $arrField[] = $val;
            }
        }
        empty($arrField) && $arrField = $this->field;

        return Db::table($this->table)->where($arrCond)->limit($offset, $limit)->order($orderby)->field($arrField)->select();
    }

    public function circleCategoryPage($param)
    {
        $conds = [
            'is_delete' => '0',//未删除
        ];
        return $this->where($conds)->paginate(10);
    }

    public function getCreateTimeAttr($value)
    {
        return date("Y-m-d H:i:m", $value);
    }

    public function getUpdateTimeAttr($value)
    {
        return date("Y-m-d H:i:m", $value);
    }

}
